import 'package:flutter/material.dart';
// import 'photos.dart';
import 'classificationList.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'common/api_service.dart'; // 导入 ApiService 类
import 'common/loading_spinner.dart'; // 导入公共组件

class CategoryPage extends StatefulWidget {
  const CategoryPage({
    super.key,
  });

  @override
  _MyCategoryPagePageState createState() => _MyCategoryPagePageState();
}

class _MyCategoryPagePageState extends State<CategoryPage> {
  List categoryList = [];
  bool isLoading = false;
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  final controller = ScrollController();

  // 调用公共方法
  void fetchData() async {
    setState(() {
      isLoading = true;
    });
    try {
      String url = 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/json/category.json'; // 替换为你的 URL
      List<dynamic> jsonData = await ApiService.fetchJsonData(url);
      // print(jsonData);
      setState(() {
        isLoading = false;
      });
      setState(() {
        categoryList = jsonData[0]['list'];
      });

    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

  Future<void> _logScreenView() async {
    await analytics.logScreenView(
      screenName: 'Category Page',
      screenClass: 'CategoryPage',
    );
    // setMessage('setCurrentScreen succeeded');
  }

  @override
  void initState() {
    super.initState();

    _logScreenView();
    fetchData();
    // categoryList = photoArrayDatas.keys.toList();
    // print(categoryList);
  }

  @override
  Widget build(BuildContext context) {
    return isLoading ? 
      const Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          LoadingSpinner()
        ],
      ) 
      :  SingleChildScrollView(
              controller: controller,
           child:  Padding(
      padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
      child: Column(
        children: [
          for (var categoryItem in categoryList) Article(classificationItem: categoryItem)
        ],
      ),
    ));
  }
}

class Article extends StatelessWidget {
  final Map<String, dynamic> classificationItem;
  const Article({
    super.key,
    required this.classificationItem,
  });

  @override
  Widget build(BuildContext context) {
    // var slug = classificationItem.replaceAll(' ', '_');
    return  GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) =>
                ClassificationListPage(classificationItem: classificationItem),
          ),
        );
      },
      child: Container(
        height: 64,
        decoration: const BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 0.5,
              color: Color.fromARGB(255, 211, 211, 211),
            ),
          ),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: 26,
              height: 26,
              child: Image.asset('images/category/${classificationItem['slug']}.webp'),
            ),
            const SizedBox(width: 10),
            Expanded(
                child: Text(
              classificationItem['category'],
              style: const TextStyle(
                fontSize: 18,
                fontFamily: 'OpenSans',
              ),
            )),
            const Icon(
              CupertinoIcons.arrow_right_circle,
              size: 30,
              color: Color.fromRGBO(0, 0, 0, .2),
            ),
          ],
        ),
      ),
    );
  }
}
